<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus';
import { getTypeId, addCategory, removeCategory, getCategoryList, updateCategory, addProduct, getProductList, delProduct } from '@/api/equipment/whm'
const typeId = ref('')
const isTableLoading = ref(false)
const categoryList = ref([])
const productList = ref([])
const treeEmptyText = ref('')
async function init() {
  treeEmptyText.value = '数据刷新中'
  await getTypeId('备品备件').then(res => {
    typeId.value = res.data.data.id
    // console.log('typeId', typeId.value)
  })
  await getCategoryList(typeId.value).then(res => {
    categoryList.value = res.data.data
    treeEmptyText.value = '暂无数据'
  })
}
init()

const categoryTreeRef = ref(null)
const materiaProps = ref({
  value: 'id',
  label: 'name',
  children: 'children',
})
const isEditCategory = ref(false);
const mainProductCategory = ref('')
function addMainProductCategory() {
  isEditCategory.value = true
}
/**
 * 新增主类别
 */
async function handleAddMainCategory() {
  if (mainProductCategory.value !== '') {
    console.log(mainProductCategory.value)
    await addCategory(mainProductCategory.value, typeId.value, 0).then(res => {
      ElMessage.success(res.data.data)
    })
    isEditCategory.value = false
  } else {
    ElMessage.error('请输入分类名称')
  }
}
/**
 * 点击左侧列表事件
 * @param val1 
 */
async function getNodeProduct(val1) {
  isTableLoading.value = true
  //根据categoryId获取子节点
  await getProductList(val1.id, typeId.value).then(res => {
    productList.value = res.data.data
  })
  isTableLoading.value = false
}
/**
 * 点击修改分类名称按钮
 */
const isEditCategoryName = ref(false);
const categoryEdit = ref({
  id: '',
  name: ''
})
function clickEditCategory(data) {
  console.log(data.name)
  categoryEdit.value.id = data.id
  categoryEdit.value.name = data.name
  isEditCategoryName.value = true

}
/**
 * 编辑类别名称
 */
async function editCategoryName() {
  console.log(categoryEdit.value)
  await updateCategory(categoryEdit.value.id, categoryEdit.value.name).then(res => {
    ElMessage.success(res.data.data)
  })
  isEditCategoryName.value = false
  init()
}
/**
 * 新增类别
 * @param data 
 */
const isAddSubCategory = ref(false);

/**
 * 新增子类别
 */
async function appendCategory() {
  console.log('append')
  await addCategory(categoryEdit.value.name, typeId.value, categoryTreeRef.value.getCurrentNode().id).then(res => {
    ElMessage.success(res.data.data)
  })
  await getCategoryList(typeId.value).then(res => {
    treeEmptyText.value = '数据刷新中'
    console.log(res)
    categoryList.value = res.data.data
    treeEmptyText.value = '暂无数据'
  })
  isAddSubCategory.value = false
  categoryEdit.value = {}
}
/**
 * 删除类别
 */
async function delCategory(data) {
  console.log(data)
  if (isTableLoading.value) {
    return
  }
  console.log(productList.value.length)
  if (productList.value.length > 0) {
    ElMessage.error('该类别下有物料，无法删除')
    return
  }
  if (data.children.length > 0) {
    ElMessage.error('该类别下有子类别，无法删除')
    return
  }
  console.log(data)
  ElMessageBox.confirm('确定删除该类别吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await removeCategory(data.id).then(res => {
      console.log(res)
      ElMessage.success(res.data.data)
      init()
    })
  })
}
/**
 * 物料信息
 */
const isEditProduct = ref(false);
const editFlag = ref(false)
const productFormRef = ref(null)
const productInfo = ref({
  id: null,
  name: '',
  code: '',
  model: '',
  unit: '',
  remark: '',
  categoryId: '',
  typeId: '',
})
const productRules = reactive({
  name: [
    { required: true, message: '请输入物料名称', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入物料编号', trigger: 'blur' },
  ],
  model: [
    { required: true, message: '请输入规格型号', trigger: 'blur' },
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' },
  ],
})
/**
 * 点击新增物料信息按钮
 */
function clickAddCategory() {
  console.log(typeof categoryTreeRef.value.getCurrentNode() === 'undefined')
  if (typeof categoryTreeRef.value.getCurrentNode() === 'undefined' || categoryTreeRef.value.getCurrentNode() === null) {
    ElMessage.error('请选择分类')
    return
  }
  isEditProduct.value = true
  productInfo.value.categoryId = categoryTreeRef.value.getCurrentNode().id
  productInfo.value.typeId = typeId.value
  editFlag.value = false
}
/**
 * 取消新增/编辑物料信息
 */
function cancelEditMeterial() {
  productInfo.value = {}
  isEditProduct.value = false
  getNodeProduct(categoryTreeRef.value.getCurrentNode())
}
/**
 * 保存物料信息
 */
async function saveProduct() {
  productFormRef.value.validate(async (val) => {
    if (val) {
      // if (editFlag.value) {
      //   console.log('这是编辑')
      // } else {
      await addProduct(productInfo.value).then(res => {
        ElMessage.success(res.data.data)
      }
      )
      // }
    } else {
      ElMessage.error('请完善表单')
      return
    }
    getNodeProduct(categoryTreeRef.value.getCurrentNode())
    isEditProduct.value = false
  })
}
/**
 * 点击编辑物料信息
 * @param row 
 */
function editProduct(row) {
  isEditProduct.value = true
  productInfo.value = row
}
/** 
 * 删除物料信息
 */
async function removeProduct(row) {
  ElMessageBox.confirm('确定删除该物料信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    console.log(row)
    delProduct(row.id).then(res => {
      ElMessage.success(res.data.data)
      getNodeProduct(categoryTreeRef.value.getCurrentNode())
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })

}
</script>

<template>
  <el-row class="container">
    <el-col :span="4" class="left">
      <h4 style="display: inline-block;">物料分类</h4>
      <el-button type="primary" size="small" style="width: 30%;margin-left: 20px;"
        @click="addMainProductCategory">新增主类别</el-button>
      <el-tree-v2 ref="categoryTreeRef" class="categoryTree" :data="categoryList" :props="materiaProps"
        @node-click="getNodeProduct" highlight-current :expand-on-click-node="false" :empty-text="treeEmptyText">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span>
              <a @click="clickEditCategory(data)"> <el-icon color="var(--el-color-primary)">
                  <Edit />
                </el-icon> </a>
              <a v-if="node.level < 3" style="margin-left: 8px" @click="isAddSubCategory = true">
                <el-icon color="var(--el-color-primary)">
                  <CirclePlusFilled />
                </el-icon> </a>
              <a style="margin-left: 8px" @click="delCategory(data)"> <el-icon color="var(--el-color-danger)">
                  <DeleteFilled />
                </el-icon> </a>
            </span>
          </span>
        </template>
      </el-tree-v2>
    </el-col>
    <el-col :span="20">
      <el-row class="container-header">
        <el-col :span="4">
          <!-- <el-text style="margin-left: 20px;">已选中{{  }}项</el-text> -->
        </el-col>
        <el-col :span="18"></el-col>
        <el-col :span="2">
          <el-button type="primary" size="small" @click="clickAddCategory">新增</el-button>
        </el-col>
        <!-- <el-col :span="2">
          <el-button type="primary" size="small" @click="clickDelCategory">删除</el-button>
        </el-col> -->
      </el-row>
      <el-row class="table">
        <el-table :data="productList">
          <!-- <el-table-column type="selection"></el-table-column> -->
          <el-table-column align="center" type="index" width="80" label="序号"></el-table-column>
          <el-table-column align="center" label="物料名称" prop="name"></el-table-column>
          <el-table-column align="center" label="物料编号" prop="code"></el-table-column>
          <el-table-column align="center" label="规格型号" prop="model"></el-table-column>
          <el-table-column align="center" label="单位" prop="unit"></el-table-column>
          <el-table-column align="center" label="备注" prop="remark"></el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="editProduct(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="removeProduct(row)">删除</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty v-loading="isTableLoading" description="暂无数据"></el-empty>
          </template>
        </el-table>
      </el-row>
    </el-col>
  </el-row>
  <el-dialog v-model="isEditProduct" title="编辑物料" width="800">
    <el-form ref="productFormRef" :model="productInfo" label-width="auto" label-position="right" :rules="productRules"
      style="margin: 8px 16px;">
      <el-form-item label="物料名称" prop="name">
        <el-input v-model="productInfo.name"></el-input>
      </el-form-item>
      <el-form-item label="物料编号" prop="code">
        <el-input v-model="productInfo.code"></el-input>
      </el-form-item>
      <el-form-item label="规格型号" prop="model">
        <el-input v-model="productInfo.model"></el-input>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="productInfo.unit"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="productInfo.remark"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" plain @click="cancelEditMeterial">取消</el-button>
      <el-button type="primary" @click="saveProduct">保存</el-button>
    </template>
  </el-dialog>
  <el-dialog title="新增主类别" v-model="isEditCategory" width="400">
    <el-input v-model.trim="mainProductCategory">
      <template #prepend>
        <el-text>主类别名称</el-text>
      </template>
    </el-input>
    <template #footer>
      <el-button type="primary" @click="handleAddMainCategory">确认</el-button>
    </template>
  </el-dialog>
  <el-dialog title="修改分类名称" v-model="isEditCategoryName" width="400">
    <el-input v-model.trim="categoryEdit.name">
      <template #prepend>
        <el-text>类别名称</el-text>
      </template>
    </el-input>
    <template #footer>
      <el-button type="primary" @click="editCategoryName">确认</el-button>
    </template>
  </el-dialog>
  <el-dialog title="新增子类别" v-model="isAddSubCategory" width="400">
    <el-input v-model.trim="categoryEdit.name">
      <template #prepend>
        <el-text>子类别名称</el-text>
      </template>
    </el-input>
    <template #footer>
      <el-button type="primary" @click="appendCategory">确认</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
.left {
  border-right: 1px dashed #ccc;
}

.container-header {
  margin: 12px 0;

  .el-button {
    width: 80%;
  }
}

.categoryTree {
  height: calc(100vh - 200px);
  // max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>